package top.kaoshanji.p1ch01d;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * 代码清单 p1ch01d-01：使用try语句进行资源管理简单示例(1.5节)
 * author kaoshanji
 * ^_^
 * create time 2024/12/22 20:11
 */
public class ResourceBasicUsage {

    private static final Logger logger = LogManager.getLogger(ResourceBasicUsage.class);

    public static void main(String[] args) {
        logger.info("...代码清单 p1ch01d-01：使用try语句进行资源管理简单示例(1.5节)...");

        ResourceBasicUsage rbu = new ResourceBasicUsage();

        try {
            String content = rbu.readFile("C:\\my.txt");
            System.out.println(content);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    public String readFile(String path) throws IOException {

        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(String.format("%n"));
            }

            return builder.toString();
        }

    }

}
